using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Killboard.Models;

namespace Killboard.Controllers
{
    public class AdminController : Controller
    {
        private const string STR_AdminPassword = "adminPassword";
        
        //
        // GET: /Admin/

        public ActionResult Index()
        {
            
            string adminPass = "";
            
            if (Session[STR_AdminPassword] != null)
            {
                adminPass = (string)Session[STR_AdminPassword];
            }
            
            KillRepository repo = new KillRepository();

            if (!repo.CheckAdminPassword(adminPass))
            {
                return RedirectToAction("SignIn");
            }


            var config = repo.GetConfiguration();

            return View("EditConfig", config);
        }

        public ActionResult EditConfig()
        {
            return Index();
        }


        public ActionResult SignIn()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SignIn(FormCollection fc)
        {
            KillRepository repo = new KillRepository();

            if (!repo.CheckAdminPassword(fc[STR_AdminPassword]))
            {
                ViewData.ModelState.AddModelError(STR_AdminPassword, "Invalid password.");
                return View();
            }

            Session.Add(STR_AdminPassword, fc[STR_AdminPassword]);

            return RedirectToAction("EditConfig");

            
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditConfig(ekbConfig config)
        {
            KillRepository repo = new KillRepository();

            config.configActive = true;
            //fix path
            string appPath = HttpContext.Server.MapPath("~");
            //string bannerURL = string.Format("~{0}", config.bannerPath.Replace(appPath, "").Replace("\\", "/"));
            //config.bannerPath = bannerURL;
            
            repo.DeactivateConfigs();
            repo.SaveNewConfig(config);

            ViewData["message"] = "Data Saved.";
            
            return View(config);
        }

        public ActionResult GetXml()
        {
            string xmlToParse = EveAPI.GetKillsXml();

            KillMailXmlParser parser = new KillMailXmlParser();
            KMParseResults results = parser.ParseXML(xmlToParse);

            return View("parseresults", results);
            
        }

    }
}
